package gazzera.node.core;

import gazzera.gui.*;
import gazzera.node.core.events.*;

import java.util.*;


public class TaskManager
{
	private Map<Task, Thread> runningTasks = new HashMap<Task, Thread>();
	final private ICore core;
	
	public TaskManager(ICore core)
	{
		this.core = core;
	}
	/*
	public void startDeferred()
	{
		deferred = false;
		// now we can start deferred task, the ones that started in the 
		// plugins "init" phase
		for (Task t : deferredTask)
		{
			startTask(t);
		}
		deferredTask = null; // reclaim memory
	}
	*/
	public void terminated(Task task)
	{
		runningTasks.remove(task);
	}
	
	public void startTask(final Task task)
	{
		final GuiInterface gui = core.getGui();
		
		Runnable r = new Runnable()
		{
			boolean interrupted = false;
			@Override
			public void run()
			{
				Object result = null;
				try
				{
					result = task.run(gui);
				}
				catch (Exception e) 
				{
					interrupted = true; 
					core.logErr(e);
				}
				finally
				{
					core.enqueue(new TaskTerminatedEvent(task, interrupted, result));
				}
				
			}
		};
		Thread t = ThreadRunner.start(r, task.getClass().getSimpleName(), true);
		runningTasks.put(task, t);
	}
	public void terminate()
	{
		for (Task t : runningTasks.keySet())
		{
		    t.interrupt();
		}
		for (Thread t : runningTasks.values())
		{
		    try
			{
		    		//t.interrupt();
				t.join();
			}
			catch (InterruptedException e)
			{
				core.logErr(e);
			}
		}
	}
	
}
